<!-- 新增角色对话框 -->
<template>
    <el-dialog v-model="dialogFormVisible" :title="form.id ? '编辑角色' : '新增角色'" width="600">
        <el-form :model="form" :rules="rules" ref="forms">
            <el-form-item prop="roleName" label="角色名称" :label-width="formLabelWidth">
                <el-input v-model="form.roleName" autocomplete="off" />
            </el-form-item>
            <el-form-item prop="roleCode" label="角色编码" :label-width="formLabelWidth">
                <el-input v-model="form.roleCode" autocomplete="off" />
            </el-form-item>
            <el-form-item label="角色描述" :label-width="formLabelWidth">
                <el-input v-model="form.remark" :rows="6" type="textarea" />
            </el-form-item>
        </el-form>
        <template #footer>
            <div class=" dialog-footer">
                <el-button @click="dialogFormVisible = false">取消</el-button>
                <el-button type="primary" @click="submit">
                    确认
                </el-button>
            </div>
        </template>
    </el-dialog>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref } from 'vue'
import { AdminRole } from '../../../api/user/type';
import $bus from '../../../bus'

let $emit = defineEmits(['editRole', 'addRole'])
const dialogFormVisible = ref(false)
const formLabelWidth = '100px'

const form = reactive<AdminRole>({
    roleName: '',
    roleCode: '',
    remark: ''
})
const forms = ref()
const rules = {
    roleName: [
        { required: true, message: '角色名称不能为空', trigger: 'blur' },
        { min: 3, max: 10, message: '长度应该在3-10之间', trigger: 'blur' },
    ],
    roleCode: [
        { required: true, message: '角色编码不能为空', trigger: 'blur' },
        { min: 3, max: 20, message: '长度应该在3-20之间', trigger: 'blur' },
    ]
}

onMounted(() => {
    $bus.on('showDialog', (obj: any) => {
        form.remark = ''
        form.roleCode = ''
        form.roleName = ''
        form.id = ''
        dialogFormVisible.value = obj.isShow
        if (obj.row) {
            Object.assign(form, obj.row)
        }
        forms.value?.clearValidate('roleName')
        forms.value?.clearValidate('roleCode')
    })
})

const submit = async () => {
    await forms.value.validate();
    if (form.id) {
        $emit('editRole', form)
    } else {
        $emit('addRole', form)
    }

    dialogFormVisible.value = false
}
</script>

<style lang="scss" scoped>
.el-form {
    padding-top: 20px;
    padding-right: 30px;
}
</style>